package com.wt.order.controller;

/**
 * @author 吴涛
 * @date 2022/5/10 16:38
 * @qq 337144203
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wt.order.common.R;
import com.wt.order.entity.Category;
import com.wt.order.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 分类管理
 */
@Slf4j
@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getAllCategory(int page,int pageSize){
        Page<Category> categoryPage = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        //调用分页方法
        categoryService.page(categoryPage,queryWrapper);
        return R.success(categoryPage);
    }


    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        log.info("category",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }


    @DeleteMapping
    public R<String> deleteCategory(Long id){
        log.info("删除分类，id为：{}",id);
        categoryService.remove(id);
        return R.success("分类信息删除成功");
    }


    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //构造一个查询条件
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据type进行查询，要先进行判断type不为空
        categoryLambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //先使用sort进行排序，相同再根据更新时间排序
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //调用查询
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return R.success(list);
    }



}
